import xlwt
import datetime
import re
import pandas as pd
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText


# 将jmeter生成的测试报告jtl文件读取出来
jtl = open('/app/oneid.jtl', 'r', encoding='utf-8')
contents = jtl.read()
# 打印没有处理的oneid.jtl
print("---------------打印oneid.jtl--------------begin")
print(contents)
print("---------------打印oneid.jtl--------------over")
wb = xlwt.Workbook()
sheet = wb.add_sheet('Sheet1')


# 把contents里面的时间戳换成具体时间
def convert_timestamps(input_string):
    # Regular expression to find timestamps (10 or 13 digits)
    timestamp_pattern = r'\b(\d{10}|\d{13})\b'

    # Find all timestamps in the input string
    timestamps = re.findall(timestamp_pattern, input_string)

    # Iterate through each timestamp and convert to date and time
    for timestamp in timestamps:
        timestamp_int = int(timestamp)
        if len(timestamp) == 13:
            timestamp_int = timestamp_int // 1000  # Convert milliseconds to seconds
        date_time = datetime.datetime.fromtimestamp(timestamp_int).strftime('%Y-%m-%d %H:%M:%S')
        input_string = input_string.replace(timestamp, date_time)

    return input_string


output_string = convert_timestamps(contents)
print(output_string)

# 将上一步获取的测试报告内容，以换行(\n)和‘，’为间隔，写入excel

rows = output_string.split('\n')
for row_idx, row in enumerate(rows):
    columns = row.split(',')
    for col_idx, value in enumerate(columns):
        sheet.write(row_idx, col_idx, value)

wb.save('output6.xls')

# 读取Excel文件
excel_file = "output6.xls"  # 指定要转换的Excel文件路径
df = pd.read_excel(excel_file)

# 将Excel数据转换为HTML表格
html_table = df.to_html()

# 将HTML表格写入文件
with open('output.html', 'w', encoding='utf-8') as file:
    file.write(html_table)

print("Excel文件已成功转换为HTML。")
# Read the HTML file 注意：encoding='utf-8'

with open('output.html', encoding='utf-8') as file:
    html_content = file.read()

# Parse the HTML content
soup = BeautifulSoup(html_content, 'html.parser')

# Find all <td> tags,遍历html文件，将<td>标签的True加上绿色，False加上红色
for td in soup.find_all('td'):
    if td.text.strip() == 'False':
        td.string.wrap(soup.new_tag('font', color='red'))
    if td.text.strip() == 'True':
        td.string.wrap(soup.new_tag('font', color='green'))

# Write the modified HTML content to a new file
with open('output.html', 'w') as file:
    file.write(str(soup))

print("HTML file has been processed successfully.")

mail_host = "smtp.163.com"
port_ = 465
# 账密需要读取/app/mail.txt


receivers = ["191865188@qq.com"]
# receivers = ["wangxiaoliang30@h-partners.com"]

# 读取html文件内容# HTML文件默认和当前文件在同一路径下，若不在同一路径下，需要指定要发送的HTML文件的路径
# 在linux中需要将'gbk'改为'utf-8'
f = open('output.html', encoding='utf-8')

# 打印处理好的output.html
print("---------------打印output.html--------------begin")
with open('output.html', 'r', encoding='utf-8') as file:
    html_content = file.read()
    print(html_content)
print("---------------打印output.html--------------over")
# mail_body = "测试邮件内容"
mail_body = f.read()
# f.close()

# 重复发同一个html的邮件内容给其他邮箱，会被163拦截，这个需要注意
message = MIMEText(mail_body, 'html', 'utf-8')
# message = MIMEText("nihao,我是测试报告2024-05-18")
message['Subject'] = 'Subject of the Email'
message['From'] = account
message['To'] = ", ".join(receivers)

try:
    smtp_ = smtplib.SMTP_SSL(mail_host, port=port_)
    smtp_.login(user=account, password=password)
    smtp_.sendmail(account, receivers, message.as_string())
except smtplib.SMTPServerDisconnected as e:
    print(f"Server unexpectedly disconnected: {e}")
except smtplib.SMTPException as e:
    print(f"An SMTP error occurred: {e}")
finally:
    smtp_.quit()
